package com.itheima.day15.TCP.test2;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

// 接收端
public class ServerDemo {
    public static void main(String[] args) {
        // 1.创建ServerSocket对象
        int port = 10002;
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream is = null;
        lo:
        while (true) {
            // 2.等待客户端连接
            try {
                Socket accept = ss.accept();

                // 3.创建字节输入流对象，接收数据
                is = accept.getInputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len = is.read(bytes)) != -1) {
                    String str = new String(bytes, 0, len);
                    if ("886".equals(str.trim())) {
                        System.out.println("\n---------系统提示：接收关闭---------");
                        break lo;
                    }
                    System.out.println(str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 4.关闭接收端，释放资源
        if (ss != null) {
            try {
                ss.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
